package com.yzycoc.hamster.demo.time202507.info;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.yzycoc.hamster.demo.common.ImageDownloadUtil;
import com.yzycoc.hamster.demo.time202507.info.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

/**
 * 抓取img.lolimi.cn 的图片
 * 创建时间： 2025/7/4
 *
 * @version 1.0
 **/
@Slf4j
public class GalleryParser {

    private final String COOKIE_ALL = "remember_web_59ba36addc2b2f9401580f014c7f58ea4e30989d=eyJpdiI6Ik5sSUs2ekt1cmg3ZkJkWEpPelNkQnc9PSIsInZhbHVlIjoiZDgrQ1BISkpWSXFaSTl6YmF5M2RheXRsMFNqa2NKcE5SSjg3bDhuNUJScmQyQzFmb2ZjL3ZuSXMxNjZ6OUVJdWp4OWJDMGhkQXhmOExHM1FmcTUzejgvVHk2UmM4QnRMb0NvRFU1UVUwQzhwVTlZMit0cHRTZW1VRW51b3dnZi9QOFpGcFlsdmpiZ0VZcm56a0ltMEF0U0JoVmdLOWVCZDZrSXJQeVd3QWJvYVpjWVcrd3IxcUUxWTFnTGpLakFEaUlNK1VaNFpiOUttVldkNHBTbEs3dDgxR29mUGdLRlhHUmpORWNlaWUxdz0iLCJtYWMiOiJjOTVhOWI5NDUzM2ZmNjliNjBjNjRkYjY4MzUxODQzZDQ3ZTM5NWFjZWU0NmI5ZWEzNTJlNzBjYTczZjEyODNhIiwidGFnIjoiIn0%3D; XSRF-TOKEN=eyJpdiI6IlpsbDBRd0ZYaHpKREJIUlBjOUx1Unc9PSIsInZhbHVlIjoialdXNGNnRDhGeFpQWitxQWo4ZGI3VkVBNEdHWXo4SzFEaXloa1psL2d4UHZ3ME43TnhMU1I4ZXA1aWxUaTZ6RWUwQWdVSC9RVlJiQytEaGhSYTN0cnFsbXFZeWNjOHdhYWF0ZzFJc2c2NXBPSU5UQUl6UnNNQjlKVDVjOEdjdVMiLCJtYWMiOiI3NjZiOTYxZjJhYmM3ZjBiZjA5ODI0NWZhNWNlZTE3OTJiNGYxMDE1N2JjZWE2NTY1YTJkYWJlMTg0NDhjYjRiIiwidGFnIjoiIn0%3D; lsky_pro_session=eyJpdiI6IkpacXBobExBS010U3paRHNnKytMV0E9PSIsInZhbHVlIjoiMmUwUlNLdnBWUy8xVWdNQVdIeXduOVEvRU1jM28yZ0JhVmZtcDFDVzBWM0h5TkJVNE96YThjVGNFenVhdFdLQU14dlZtaUliSWZtaUh2T0R5S3orc3FKVUFRVkEvSnhFQ1NDVEVwSE1zSkI5Y2xHQXBid0hwT0pDZytzZXhvcXMiLCJtYWMiOiJlZTI0MDQxNWFiMTk5MjdhNjhmMTY2MTYyMmUyYWNlY2EyOGVkYTZlYTVkYzA0OGMxZDE2NDJjOTNhZWY2ZmMzIiwidGFnIjoiIn0%3D";

    private String COOKIE_TITLE = "";

    private String COOKIE_XSRF_TOKEN = "";

    private String COOKIE_LSKY_PRO_SESSION = "";


    public GalleryParser() {
        String[] split = COOKIE_ALL.split(";");
        COOKIE_TITLE = split[0];
        COOKIE_XSRF_TOKEN = split[1];
        COOKIE_LSKY_PRO_SESSION = split[2];

    }

    // 拼接成合法的 Cookie 请求头格式
    public String getCookieHeader() {
        return COOKIE_TITLE + ";" + COOKIE_XSRF_TOKEN + ";" + COOKIE_LSKY_PRO_SESSION;
    }

    // 根据响应中 Set-Cookie 更新全局 Cookie
    public void updateCookieFromResponse(HttpResponse response) {
        List<String> setCookies = response.headers().get("Set-Cookie");
        for (String setCookie : setCookies) {
            String[] split = setCookie.split(";");
            if (setCookie.contains("XSRF-TOKEN")) {
                COOKIE_XSRF_TOKEN = split[0];
            }
            if (setCookie.contains("lsky_pro_session")) {
                COOKIE_LSKY_PRO_SESSION = split[0];
            }
        }
    }


    public boolean getData(Integer page, ImageDownloadUtil imageDownloadUtil) {
        String url = "https://img.lolimi.cn/gallery?page=" + page;
        log.info("请求：{}", url);
        HttpResponse response = HttpRequest.get(url)
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:140.0) Gecko/20100101 Firefox/140.0")
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                .header("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
                .header("Accept-Encoding", "gzip, deflate, br, zstd")
                .header("Connection", "keep-alive")
                .header("Referer", "https://img.lolimi.cn/gallery")
                .header("Cookie", getCookieHeader())
                .header("Upgrade-Insecure-Requests", "1")
                .header("Sec-Fetch-Dest", "document")
                .header("Sec-Fetch-Mode", "navigate")
                .header("Sec-Fetch-Site", "none")
                .header("Sec-Fetch-User", "?1")
                .header("Pragma", "no-cache")
                .header("Connection", "close")
                .header("Cache-Control", "no-cache")
                .setConnectionTimeout(120_000)
                .setReadTimeout(60_000)
                .execute();
        updateCookieFromResponse(response);
        if (response.isOk()) {
            String html = response.body();
            List<ImageInfo> list = parseHtml(html);
            for (ImageInfo imageInfo : list) {
                imageDownloadUtil.generateInsertSql(imageInfo.getImageUrl(), "30", imageInfo.getAuthor(), "'image.lolimi.cn'");
            }
            log.info("响应成功:{}\t,获取{}条数据", url, list.size());
            return true;
        } else {
            log.info("请求:{}\t失败：" + response.getStatus(), url);
            return false;
        }
    }


    private static List<ImageInfo> parseHtml(String html) {
        List<ImageInfo> resultList = new ArrayList<>();
        Document document = Jsoup.parse(html);

        // 筛选所有 grid-item 元素
        Elements gridItems = document.select("div.grid-item");

        for (Element item : gridItems) {
            Element imageLink = item.selectFirst("a[href^=https://image.lolimi.cn]");
            Element authorTag = item.selectFirst("p");

            if (imageLink != null && authorTag != null) {
                ImageInfo info = new ImageInfo();
                info.setImageUrl(imageLink.attr("href"));
                info.setAuthor(authorTag.text());
                resultList.add(info);
            }
        }

        return resultList;
    }


}
